package com.codeying.servlet;

import com.codeying.entity.*;
import com.codeying.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

import com.codeying.utils.*;

import java.util.Date;

import com.codeying.servlet.AbsServlet;

/**
 * 用于注册的Servlet
 */
@WebServlet("/register")
public class RegisterServlet extends AbsServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        //获取用户账号密码，用户类型
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String usertype = req.getParameter("usertype");
        if (MyUtils.isEmpty(username) || MyUtils.isEmpty(password)) {
            req.setAttribute("message", "用户名密码不可为空！");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }//${property.frnkey.nameLow}List
        if (usertype.equals("admin")) {
            Admin temp = adminService.getBy("username", username);
            if (temp != null) {
                req.setAttribute("message", "账号已存在！");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            }
            Admin admin = new Admin();
            admin.setId(CommonUtils.newId());
            admin.setUsername(username);
            admin.setPassword(password);
            String name = ""; //姓名
            String tele = ""; //电话
            adminService.insert(admin);
            req.setAttribute("message", "注册成功，请登陆");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        if (usertype.equals("user")) {
            User temp = userService.getBy("username", username);
            if (temp != null) {
                req.setAttribute("message", "账号已存在！");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            }
            User user = new User();
            user.setId(CommonUtils.newId());
            user.setUsername(username);
            user.setPassword(password);
            String name = ""; //姓名
            String gender = ""; //性别
            String tele = ""; //电话
            String email = ""; //邮箱
            userService.insert(user);
            req.setAttribute("message", "注册成功，请登陆");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        //注册失败
        req.setAttribute("message", "请选择角色类型");
        req.getRequestDispatcher("/register.jsp").forward(req, resp);

    }

}

